from django import forms
from django.utils.safestring import mark_safe
        
class TokenTextBoxWidget(forms.TextInput):
    
    def __init__(self, attrs=None, init_function=None, separators=',', ac_options=''):
        super(TokenTextBoxWidget, self).__init__(attrs)
        self.ac_options = ac_options
        self.separators = separators
        self.init_function = init_function

    def render(self, name, value, attrs=None):
        html = super(TokenTextBoxWidget, self).render(name, value, attrs)
        if self.init_function is not None:
            html += u'<script type="text/javascript"> \
                          %s("%s"); \
                      </script>' % (self.init_function, name)
        else:
            html += u'<script type="text/javascript"> \
                          $(document).ready(function() { \
                              $("input[name=%s]").tokentextbox({ \
                                 separators: "%s", \
                                 autocomplete_options: %s \
                             }); \
                          }); \
                      </script>' % (name, self.separators, self.ac_options)
        return mark_safe(html)
    
    class Media:
        js = (
            'js/jquery-latest.js',
            'js/tokentextbox/jquery.autocomplete.tweaked.js',
            'js/tokentextbox/jquery.parentautocomplete.js',
            'js/tokentextbox/jquery.tokentextbox.js',
            'js/tokentextbox_init.js',
        )
        css = {
            'screen': (
                'js/tokentextbox/jquery.autocomplete.css',
                'js/tokentextbox/jquery.tokentextbox.css',
            )
        }